﻿using SecureDataCMS.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SecureDataCMS.Controllers
{

    public class NewLoginController : Controller
    {
        //Set these to set the types. stripped from the DB
        const int ADMINISTRATORTYPE = 1;
        const int APPROVERTYPE = 2;
        const int PRIMARYINVTYPE = 3;
        const int DATAMANAGERTYPE = 5;
        const int RESEARCHERTYPE = 4;

        const int VALIDFORHOURS = 1;

        private SECCMS_liveEntities myDB = new SECCMS_liveEntities();
        //
        // GET: /NewLogin/

        public ActionResult Index()
        {
            //Returns the view. That then posts to Index.
            return View();
        }

        // POST: /NewLogin/
        [HttpPost]
        public ActionResult Index(NewLoginModel login)
        {
            Random randKeyGen = new Random(); //Oh yeah, I'm not an idiot
            int key = 0;
            int userLevel = 0;
            int keystatus = 1;
            //Begin make-sure-the-key-isn't-taken
            while (keystatus == 1)
            {
                keystatus = 0;
                key = randKeyGen.Next();
                //Otherwise, all good.
                var prevReq = (from l in myDB.tblLogins
                               where l.LoginID == key
                               select l);
                if (prevReq.Count() != 0)
                {
                    if(prevReq.First().dtmCreated.AddHours(prevReq.First().intHoursValid) < DateTime.Now)
                    {
                        foreach(var item in prevReq.ToList())
                        {
                            myDB.tblLogins.Remove(item);
                        }
                        myDB.SaveChanges();
                    }
                    keystatus = 1;
                }
            }
            tblLogin newLog = new tblLogin();
            newLog.LoginKey = key;
            
            var users = (from u in myDB.tblUsers
                            where u.strEmail.Equals(login.UserName)
                            select u);
            if (users.Count() == 0)
            {
                return Redirect("/");
            }
            var user = users.First();

                //Note, this return needs to occur OUTSIDE the loop, so we can assign the HIGHEST privileges. -- that's done, disregard this statement.
                if(user.strEmail.Equals(login.UserName) && (user.strPassword.Equals(login.Password)))
                {
                    newLog.UserID = user.UserID;
                    newLog.intHoursValid = VALIDFORHOURS;
                    newLog.dtmCreated = DateTime.Now;

                    HttpCookie cookie;
                    if (user.UserTypeID == ADMINISTRATORTYPE)
                    {
                        cookie = new HttpCookie("loginCookie")
                        {
                            Expires = DateTime.Now.AddHours(VALIDFORHOURS),
                            Value = key.ToString() //Note to self, come up wiot
                        };
                        Response.SetCookie(cookie);
                        if(userLevel ==0 || userLevel > 1)
                        {
                            userLevel = 1;
                        }
                    }
                    else if(user.UserTypeID == APPROVERTYPE)
                    {
                        cookie = new HttpCookie("loginCookie")
                        {
                            Expires = DateTime.Now.AddHours(VALIDFORHOURS),
                            Value = key.ToString() //Note to self, come up wiot
                        };
                        Response.SetCookie(cookie);
                        if (userLevel == 0 || userLevel > 2)
                        {
                            userLevel = 2;
                        }
                    }
                    else if(user.UserTypeID == PRIMARYINVTYPE)
                    {
                        cookie = new HttpCookie("loginCookie")
                        {
                            Expires = DateTime.Now.AddHours(VALIDFORHOURS),
                            Value = key.ToString() //Note to self, come up wiot
                        };
                        Response.SetCookie(cookie);
                        if (userLevel == 0 || userLevel > 3)
                        {
                            userLevel = 3;
                        }
                    }
                    else if(user.UserTypeID == DATAMANAGERTYPE)
                    {
                        cookie = new HttpCookie("loginCookie")
                        {
                            Expires = DateTime.Now.AddHours(VALIDFORHOURS),
                            Value = key.ToString() //Note to self, come up wiot
                        };
                        Response.SetCookie(cookie);
                        if (userLevel == 0 || userLevel > 4)
                        {
                            userLevel = 4;
                        }
                    }
                    else if(user.UserTypeID == RESEARCHERTYPE)
                    {
                        cookie = new HttpCookie("loginCookie")
                        {
                            Expires = DateTime.Now.AddHours(VALIDFORHOURS),
                            Value = key.ToString() //Note to self, come up wiot
                        };
                        Response.SetCookie(cookie);
                        if (userLevel == 0 || userLevel > 5)
                        {
                            userLevel = 5;
                        }
                    }
                }

                
 
            if(userLevel == 5)
            {
                myDB.tblLogins.Add(newLog);
                myDB.SaveChanges();
                return Redirect("/ControlPanel/PrimInv");
            }
            else if (userLevel == 4)
            {
                myDB.tblLogins.Add(newLog);
                myDB.SaveChanges();
                return Redirect("/ControlPanel/PrimInv");
            }
            else if (userLevel == 3)
            {
                myDB.tblLogins.Add(newLog);
                myDB.SaveChanges();
                return Redirect("/ControlPanel/PrimInv");
            }
            else if (userLevel == 2)
            {
                myDB.tblLogins.Add(newLog);
                myDB.SaveChanges();
                return Redirect("/ControlPanel/Approver");
            }
            else if (userLevel == 1)
            {
                myDB.tblLogins.Add(newLog);
                myDB.SaveChanges();
                return Redirect("/ControlPanel/Admin");
            }
            
            ViewBag.Error = "Username and/or Password invalid.";
            return View();
        }
        public ActionResult Logout()
        {
            HttpCookie cookie;
            cookie = new HttpCookie("loginCookie")
            {
                Expires = DateTime.Now,
                Value = "" //Note to self, come up wiot
            };
            Response.SetCookie(cookie);

            return Redirect("/");
        }

    }
}
